package My.project.Ui.Activity;

import My.project.Ui.R;
import My.project.Util.Connector;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * This activity is used to display the log in page.
 * It can automatically check the fields of the form.
 * And after the user logged in successfully, it will
 * redirect to where the user comes from: Record or List
 * Users.
 * It can return to the MainActivity by click the home button.
 * @author Bell
 *
 */
public class LogInActivity extends Activity {
	
	private Button submitButton;
	private Button registerButton;
	private EditText et;
	private String next;
	private Bundle bundle;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        // enable home button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        
        // Get the redirect message from the intent
	    Intent intent = this.getIntent();
	    bundle = intent.getExtras();
	    next = bundle.getString("nextActivity");

        submitButton = (Button)findViewById(R.id.button_login);
        submitButton.setOnClickListener(new Button.OnClickListener(){
        	public void onClick(View v){
        		et = (EditText) findViewById(R.id.username);
        		String userName = et.getText().toString();
        		
        		et = (EditText) findViewById(R.id.password);
        		String password = et.getText().toString();
        		
        		// check the fields
        		if (userName.equals("")) {
        			showToast("Please fill in user name");
        		} else if (password.equals("")) {
        			showToast("Please fill in password");
        		} else {
        			// connect to server
            		Connector con = new Connector();
            		String res = con.Login(userName, password);
            		
            		if (res.equals("Welcome!")) {
            			redirect();
            		} else 
            			showToast(res); // show error information
        		}
        	}
        });
        
        registerButton = (Button) findViewById(R.id.button_register);
        registerButton.setOnClickListener(new Button.OnClickListener() {
        	public void onClick(View v) {
        		Intent intent = new Intent();
        		intent.setClass(LogInActivity.this, RegisterActivity.class);
        		// put the redirect information in intent
        		intent.putExtras(bundle);
        		
        		startActivity(intent);
        	}
        });

    }

    //menu button action
  	@Override
  	public boolean onCreateOptionsMenu(Menu menu) {
  		menu.add(0, 0, 0, R.string.str_about);
  		menu.add(0, 1, 1, R.string.str_exit);
  	    return true;
  	}

  	@Override
  	public boolean onOptionsItemSelected(MenuItem item) {
  		super.onOptionsItemSelected(item);
  		switch(item.getItemId()){
  		case android.R.id.home:
              // This is called when the Home (Up) button is pressed
              // in the Action Bar.
              Intent parentActivityIntent = new Intent(
              		this, MainActivity.class);
              parentActivityIntent.addFlags(
                      Intent.FLAG_ACTIVITY_CLEAR_TOP |
                      Intent.FLAG_ACTIVITY_NEW_TASK);
              startActivity(parentActivityIntent);
              finish();
              break;
  		case 0:
  			openOptionsDialog();
  			break;
  		case 1:
  			exitOptionsDialog();
  			break;
  		default:
  			break;
  		}
  		return true;
  	}
  	
  	// show author info
  	private void openOptionsDialog(){
  		new AlertDialog.Builder(this).setTitle(R.string.str_about)
  		.setMessage(R.string.app_about_msg)
  		.setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener(){
  			public void onClick(DialogInterface dialoginterface, int i){
  				
  			}
  		}).show();
  	}

  	// show exit dialog
  	private void exitOptionsDialog(){
  		new AlertDialog.Builder(this).setTitle(R.string.str_exit)
  		.setMessage(R.string.app_exit_msg)
  		.setNegativeButton(R.string.str_no, new DialogInterface.OnClickListener(){
  			public void onClick(DialogInterface dialoginterface, int i){
  				
  			}
  		})
  		.setPositiveButton(R.string.str_yes, new DialogInterface.OnClickListener(){
  			public void onClick(DialogInterface dialoginterface, int i){
  				Intent intent = new Intent(Intent.ACTION_MAIN);
  	            intent.addCategory(Intent.CATEGORY_HOME);
  	            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  	            startActivity(intent);
  	            android.os.Process.killProcess(android.os.Process.myPid());
  			}
  		}).show();
  	}
	
  	// redirect to where user comes from
	private void redirect() {
		Intent intent = new Intent();
		if (next.equals("record")) {
			intent.setClass(LogInActivity.this, RecordActivity.class);
		} else if (next.equals("friend")) {
			intent.setClass(LogInActivity.this, ListUserActivity.class);
		}
		startActivity(intent);
		this.finish();
	}
	
	private void showToast(String msg) {
		Context context = getApplicationContext();
		int duration = Toast.LENGTH_SHORT;
		Toast.makeText(context, msg, duration).show();
	}
}